import router from '@/router';
import store from 'store2';
import axios from 'axios';
import _ from 'lodash';

/**
 * CONF & JWT
 * @author haaid <me@wanghaida.com>
 * @date 2019-04-19 12:41:52
 */
axios.defaults.baseURL = process.env.VUE_APP_API;
// request
axios.interceptors.request.use((config) => {
    // 解决获取 geojson 资源受 baseURL 影响的问题
    if (config.url.includes('.geojson')) {
        // eslint-disable-next-line
        config.baseURL = '';
    }
    // 判断是否存在 Token，如果存在，则每个 Request 都加上 Token
    if (store('token')) {
        // eslint-disable-next-line
        config.headers.Authorization = `Bearer ${store('token')}`;
    }
    return config;
}, error => Promise.reject(error));
// response
axios.interceptors.response.use(response => response, (error) => {
    if (error.response) {
        switch (error.response.status) {
            // 状态码为 401 时清空 Local Storage
            case 401:
                store(false);
                router.push({ path: '/401' });
                break;
            case 403:
                router.push({ path: '/403' });
                break;
            default:
                // router.push({ path: '/500' });
        }
    }
    return Promise.reject(error);
});

/**
 * 远程接口
 * @author haaid <me@wanghaida.com>
 * @date 2019-04-19 12:41:52
 */
export default {
    /**
     * GET 请求
     */
    get(url, params, callback, catchCallback) {
        axios.get(url, { params }).then((response) => {
            if (_.isFunction(callback)) {
                callback(response.data);
            }
        }).catch((error) => {
            if (_.isFunction(catchCallback)) {
                catchCallback(error);
            }
        });
    },
    /**
     * POST 请求
     */
    post(url, data, callback, catchCallback) {
        axios.post(url, data).then((response) => {
            if (_.isFunction(callback)) {
                callback(response.data);
            }
        }).catch((error) => {
            if (_.isFunction(catchCallback)) {
                catchCallback(error);
            }
        });
    },
    /**
     * 登录
     * @author haaid <me@wanghaida.com>
     * @date 2019-04-19 12:53:39
     */
    login(data, callback, catchCallback) {
        this.post('/api/v1/login', data, callback, catchCallback);
    },
};
